package com.gitee.minimalismstyle.fresh.common.web.extra

import org.apache.commons.fileupload.FileItem
import org.apache.commons.fileupload.FileItemFactory
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.commons.CommonsMultipartFile
import java.io.File
import java.io.FileInputStream

fun File.toMultipartFile(): MultipartFile {
    return CommonsMultipartFile(createFileItem(this));
}

private fun createFileItem(file: File): FileItem {
    val factory: FileItemFactory = DiskFileItemFactory(16, null)
    val item: FileItem = factory.createItem("textField", "text/plain", true, file.name)
    var bytesRead = 0
    val buffer = ByteArray(8192)
    item.outputStream.use { os ->
        FileInputStream(file).use { fis ->
            while (fis.read(buffer, 0, 8192).also { bytesRead = it } != -1) {
                os.write(buffer, 0, bytesRead)
            }
        }
    }
    return item
}